package it.csi.finregio.finreges.util.parser;

import java.io.OutputStream;
import java.io.Reader;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;

import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.Element;
import com.lowagie.text.List;
import com.lowagie.text.ListItem;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.rtf.RtfWriter2;

public class HTMLtoRTF {

	public static  void convert(OutputStream out,Reader theHtml) throws Exception{
		Document doc = new Document();
		
		RtfWriter2 rtfWriter = RtfWriter2.getInstance(doc,
		out);
//		PdfWriter rtfWriter = PdfWriter.getInstance(doc,
//		new FileOutputStream("c:/my.pdf"));
		doc.open();
		ArrayList p = HTMLWorker
				.parseToList(theHtml,null);
//						new InputStreamReader(
//								HTMLReader.class
//										.getResourceAsStream("/it/csi/finregio/finreges/presentation/parser/Anteprima.htm")),
//						null);
		for (int k = 0; k < p.size(); ++k) {
			Element el = (Element) p.get(k);
			if(el instanceof List){
				parseElements(el);
			}
			doc.add(el);
		}
		doc.close();
	}
	

	/**
	 * @param el
	 */
	private static void parseElements(Element el) {
		List l = (List) el;
//				System.out.println(l);
		ArrayList items = l.getItems();
		for (Iterator iterator = items.iterator(); iterator.hasNext();) {
			Object obj = (Object) iterator.next();
			if(obj instanceof ListItem){
				ListItem item =(ListItem) obj;
				System.out.println("--> "+item+" ==> "+item.getIndentationLeft());
				ArrayList chunks = item.getChunks();
				Collection chuncksToRemove = new ArrayList();
//				System.out.println(chunks);
				for (Iterator itChuncks = chunks.iterator(); itChuncks
						.hasNext();) {
					Chunk chunk = (Chunk) itChuncks.next();
					if(chunk.getContent().equals("\n")){
						chuncksToRemove.add(chunk);
					}
				}
				for (Iterator iterator2 = chuncksToRemove.iterator(); iterator2
						.hasNext();) {
					Chunk toRemove = (Chunk) iterator2.next();
					item.remove(toRemove);
				}
//						System.out.println(chunks);
			}
			if (obj instanceof List) {
				List aList = (List) obj;
				parseElements(aList);
				
			}
		}
	}

	
}
